import { util } from '../../../../utils/util'
var dateTimePicker = require('../../../../utils/dateTimePicker');
let app = getApp();
Page({
  data:{
    reject_hide:0,
    rejectReason: '',
    rejectType:'',
    input_Boolean:true,
    grade_name: '--请选择--',
    grades: [{id:21,value:'信息不符，给予退回'}, {id:22,value:'信息不符评价项，给予退回'}, {id:23,value:'图片信息不清晰，请重新提交'},{id:24,value:'资料不全，给予退回'},{id:25,value:'其他'} ],
    dealType: '',   //处理类型，（1确认，2驳回）
    //实例id
    instanceId :'',
    dealStatus:0, //教师进来时已处理不显示按钮0   未处理显示1
    from_sxdt_type : 1,

    hide : '0',    //点击修改后变化
    Role:'',
    activityType:'',        //活动类型
    activityTypeString:'',  //互动类型对应的中文
    instanceType:'',        //实例类型
    instanceTypeString:'',  //实例类型对应的中文
    status:'',              //当前实例状态
    statusString:'',        //状态对应的中文
    dealLog:'',              //拒绝原因
    imgNubmer:9,  //图片数量
    honor_name:'',
    honorName:'',
    organizations:'',
    organizer:'',
    examines:'',
    examines_name:'',
    startYear: util.formatDateTimeYearFive(new Date()),
    endYear: util.formatDateTimeYear(new Date()),
    beginTime:'',
    endTime:'',
    honorType:'',
    //图片数组
    files:[],
    //选择获奖类型
     //考核情况
     examines:'',
     gradeArr:[
        {css:'',id:'1',value:'国家级'},{css:'',id:'2',value:'省级'},{css:'',id:'3',value:'市级'},{css:'',id:'4',value:'县级'},{css:'',id:'5',value:'校级'}
    ], 
    kh_gradeArr:[
        {css:'',id:'1',value:'合格'},{css:'',id:'2',value:'不合格'}
    ],
  },
  onLoad(query) {
    let _this=this;
    // 页面加载
    console.info(`Page onLoad with query: ${JSON.stringify(query)}`+app.Role);
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    obj.dateTimeArray.pop();
    this.setData({
      dateTimeArray: obj.dateTimeArray,
      dateTime1: obj.dateTime,
      dateTime2: obj.dateTime,
      dateTime: obj.dateTime
    });


    this.setData({
      instanceId: query.instanceId,
      Role:app.Role,
      honorType:'',
        //图片数组
      files:[],
       gradeArr:[
        {css:'',id:'1',value:'国家级'},{css:'',id:'2',value:'省级'},{css:'',id:'3',value:'市级'},{css:'',id:'4',value:'县级'},{css:'',id:'5',value:'校级'}
        ],
        kh_gradeArr:[
        {css:'',id:'1',value:'合格'},{css:'',id:'2',value:'不合格'}
    ],
    hide : '0',    //初始化显示状态防止被缓存出现bug的情况
    });

    //1，获取写实记录详情
    util.getDetail(query.instanceId).
    then(function(res) {
      var data = JSON.parse(res.data);
            _this.setData({
              activityType:res.activityType,
              activityTypeString:res.activityTypeString,
              instanceType:res.instanceType,
              instanceTypeString:res.instanceTypeString,
              status:res.status,
              statusString:res.statusString,
              dealLog:res.dealLog,
              //-------
              files:data.files,
              organizations:data.organizations,
              organizer:data.organizer,
              examines:data.examines,
              examines_name:_this.data.kh_gradeArr[data.examines-1].value,
              beginTime:data.beginTime,
              endTime:data.endTime,
              honorType:data.honorType,
              honor_name: data.honorType-1==0? _this.data.gradeArr[0].value: _this.data.gradeArr[data.honorType-1].value,
            })
    }) 
  },
  //教师处理写实
    dealRecord(rejectType,rejectReason){
      console.log('实例id：'+this.data.instanceId+'处理类型：'+this.data.dealType+'驳回类型为：'+rejectType+'驳回类型选择了其他时原因为：'+rejectReason)
      let _this=this;

       var data = {
         instanceId: _this.data.instanceId,
         dealType: _this.data.dealType,
         rejectType:rejectType,
         rejectReason:rejectReason,
      };
      util.dealRecord(data)
      .then(function(res){
        if(res==1){
          wx.setStorageSync('howmany',1)
          wx.showToast({
             title: '处理成功',
             icon: 'success',
             duration: 2000,
             success() {
                 wx.navigateBack({
                   delta: 1
                 })
               },
           });
        }else{
           util.showError(JSON.stringify(res))
        }
      });
    },
    // 点击确认
    teacherConfirm(){
      let _this=this;
      wx.showModal({
      title: '确认通过',
      content: '请确认已审核学生的写实记录',
      confirmText: '确定',
      cancelText: '取消',
      success({ confirm }) {
        if(confirm){
          console.log('确认')
          _this.setData({
            dealType:'1',
      })
          _this.dealRecord()
        }else{
          console.log('取消')
        }
      },
      fail() {
        console.log('fail');
      },
      complete() {
        console.log('complete');
      },
    });
    },

    // 点击驳回
    teacherReject(){
      this.setData({
        grade_name: '--请选择--',
        reject_hide: 1,
      })
    },

    // 点击驳回后点击取消
    cancel(){
      this.setData({
        reject_hide: 0,select: false,input_Boolean: true,
      })
    },

    // 点击驳回后点击确定
    determine(){
      let _this=this;
      let name=_this.data.grade_name;
      
      if(name!='--请选择--'){
        if(name=='其他'){
          if(_this.data.rejectReason==''){
            util.showError('驳回失败,请输入原因')
          }else{
            wx.showModal({
              title: '确认驳回',
              content: '您确定驳回该学生的写实记录吗？',
              confirmText: '确定',
              cancelText: '取消',
              success({ confirm }) {
                if(confirm){
                  _this.setData({
                    reject_hide: 0,select: false,input_Boolean: true,
                    dealType:'2',
                  })
                  _this.dealRecord(_this.data.rejectType,_this.data.rejectReason)
                }else{
                  console.log('取消')
                }  
              },
            }); 
          }
        }else{
          wx.showModal({
            title: '确认驳回',
            content: '您确定驳回该学生的写实记录吗？',
            confirmText: '确定',
            cancelText: '取消',
            success({ confirm }) {
              if(confirm){
                _this.setData({
                  reject_hide: 0,select: false,input_Boolean: true,
                  dealType:'2',
                })
                _this.dealRecord(_this.data.rejectType)
              }else{
                console.log('取消')
              }
            },
          });
        }
      }else{
        util.showError('驳回失败,请输入原因')
      }
    },

    // 点击下拉列表
    bindShowMsg() {
      this.setData({
        select: !this.data.select
      })
    },

  // 选择元素
  mySelect(e) {
    console.log(e)
    var id = e.currentTarget.dataset.item.id;
    var value=e.currentTarget.dataset.item.value;
    if(id==25){
      this.setData({
        rejectReason: '',
        input_Boolean: false
      })
    }else{
      this.setData({
        input_Boolean: true
      })
    }
    this.setData({
      grade_name: value,
      rejectType: id,
      select: false
    })
  },

  // 获取input中的值
  reasonKey(e) {
    this.setData({
      rejectReason: e.detail.value,
    });
  },

  // 点击修改
  on_modify(){
      var me = this;

      let arr=me.data.gradeArr;
      var index = me.data.honorType-1;
      for(let i=0;i<arr.length;i++){arr[i].css=''}
      arr[index].css = ' active';
      me.data.honorType=arr[index].id;

      let gradeArr=me.data.kh_gradeArr;
      var gradeArrIndex = me.data.examines-1
      for(let i=0;i<gradeArr.length;i++){gradeArr[i].css=''}
      gradeArr[gradeArrIndex].css = ' active';
      me.data.examines=arr[gradeArrIndex].id;

      me.setData( me.data);
      this.setData({
        hide:'1'
      })
  },

  on_grade(e){
      var me = this;
      console.log(e.currentTarget.dataset.index)
      let index=e.currentTarget.dataset.index;
      let arr=me.data.gradeArr;
      let i=0;
      for(;i<arr.length;i++){arr[i].css=''}
      arr[index].css = ' active';
      me.data.honorType=arr[index].id;
      me.setData( me.data);
    },
    onkh_grade(e){
      var me = this;
      console.log(e.currentTarget.dataset.index)
      let index=e.currentTarget.dataset.index;
      let arr=me.data.kh_gradeArr;
      let i=0;
      for(;i<arr.length;i++){arr[i].css=''}
      arr[index].css = ' active';
      me.data.examines=arr[index].id;
      me.setData( me.data);
    },
    //学生作废该条记录
    on_delete(){
      var me =this;
      wx.showModal({
        title: '提示',
        content: '确定要删除此条写实记录吗？',
        confirmText: '确定',
        cancelText: '取消',
        success: function (res) {
          if (res.confirm) {

          util.invalid(me.data.instanceId);

          } else if (res.cancel) {
            console.log('点击取消了');
            return false;
          }
        }
      })
    },
    //学生再次提交
    onSubmit(e) {
      var me = this;
      var obj = e.detail.value;
      var dataObj=obj;
      dataObj['files'] = me.data.files;
      dataObj['honorType'] =me.data.honorType;
      dataObj['examines'] = me.data.examines;
      //做非空校验
      if(util.validation(dataObj)){
          obj['honorType'] = parseInt(me.data.honorType);
          obj['files'] = me.data.files;
          obj['examines'] = parseInt(me.data.examines);
          obj['activityType'] = parseInt(me.data.activityType);
          obj['instanceType'] = parseInt(me.data.instanceType);
          obj['showName'] = 'organizations';
          console.info(obj);
          var data = {
              activityType: parseInt(me.data.activityType),
              instanceType: parseInt(me.data.instanceType),
              itemInfo : obj,
              instanceId:me.data.instanceId
           }
         //提交数据
          util.submitRecord(data); 
      } 
    },
  //控制选择器的日跟随月而联动
  changeDateTimeColumn(e) {
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({ 
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },

  stateDatePickerYMDHMS(e) {
    let dateTimeArray=this.data.dateTimeArray;
    let dateTime=e.detail.value;
    let dataValue=dateTimeArray[0][dateTime[0]]+'-'+dateTimeArray[1][dateTime[1]]+'-'+dateTimeArray[2][dateTime[2]]+' '+dateTimeArray[3][dateTime[3]]+':'+dateTimeArray[4][dateTime[4]]
    //选择时间不能大于当前时间
    if(!(util.judgeDateTime(dataValue))){
      return;
    }
    //计算时间差和比较开始时间不能大于结束时间
    var statedate=new Date(dataValue.replace(/-/g, '/')).getTime();  //开始时间  
    var enddate=new Date(this.data.endTime.replace(/-/g, '/')).getTime();  //结束时间 
    if(enddate<=statedate){
      util.showError('结束时间必须大于开始时间');
      return;
    }
   this.setData({
    beginTime:dataValue,
   })
  },

  endDatePickerYMDHMS(e){
    let dateTimeArray=this.data.dateTimeArray;
    let dateTime=e.detail.value;
    let dataValue=dateTimeArray[0][dateTime[0]]+'-'+dateTimeArray[1][dateTime[1]]+'-'+dateTimeArray[2][dateTime[2]]+' '+dateTimeArray[3][dateTime[3]]+':'+dateTimeArray[4][dateTime[4]]
    //选择时间不能大于当前时间
    if(!(util.judgeDateTime(dataValue))){
      return;
    }
    //计算时间差和比较开始时间不能大于结束时间
    var statedate=new Date(this.data.beginTime.replace(/-/g, '/')).getTime();  //开始时间  
    var enddate=new Date(dataValue.replace(/-/g, '/')).getTime();  //结束时间 
    if(enddate<=statedate){
      util.showError('结束时间必须大于开始时间');
      return;
    }
   this.setData({
    endTime:dataValue,
   })
  },

  /**
   * 写实材料上传图片方法
   */
  xsuploads: function () {
    let me = this;
    wx.chooseImage({
      count: me.data.imgNubmer, // 默认9
     //钉钉中死都不能加这个，巨坑 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        util.showLoading();
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
       console.log(`Page --------: ${JSON.stringify(res)}`);
       
       for(var i=0;i<res.tempFilePaths.length;i++){
          this.me.files.push(
            res.tempFilePaths[i]
          );
          that.data.imgNubmer--;
       }
        /**
         * 上传完成后把文件上传到服务器
         */
      //   var count = 0;
      //   var files = that.data.files;
      //  for (var i = 0, res.tempFilePaths.length; i < h; i++) {
      //     //上传文件
      //     wx.uploadFile({
      //         url: app + '/common/uploadImage',
      //         fileType: 'image',
      //         filePath: res.tempFilePaths[i],
      //         fileName: 'files',
      //         header: {
      //           "Content-Type": "multipart/form-data",
      //           "Authorization" : "Bearer "+app.token,
      //         },
      //         success: function (res) {
      //           files.push(
      //             res.data.info.image
      //           );
      //         },
      //         fail: function (res) {
      //           wx.hideToast();
      //           wx.showModal({
      //             title: '错误提示',
      //             content: '上传图片失败',
      //             showCancel: false,
      //             success: function (res) { }
      //           })
      //         }
      //         ,
      //         complete: function(res) {
      //           that.setData({
      //               files
      //           })
      //           util.hideLoading();
      //         }
      //       });
      //  }
      this.setData(this.data);
      },
      fail:()=>{
        wx.showToast({
          title: 'fail', // 文字内容
        });
      },
       complete: function(res) {
            util.hideLoading();
      }
    })
  },

  /**
   * 写实预览图片方法  
   */
  doubleClick: function (e) {
    let index = e.target.dataset.index;
    let that = this;
    console.log(that.data.files[index]);
    console.log(that.data.files);
    wx.previewImage({
      current: that.data.files[index],
      urls: that.data.files,
      //这根本就不走
      success: function (res) {
        //console.log(res);
      },
      //也根本不走
      fail: function () {
        //console.log('fail')
      }
    })
  },
  /**
   * 长按删除图片
   */
  deleteImage: function (e) {
    var that = this;
    var files = that.data.files;
    var index = e.currentTarget.dataset.index;//获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          that.data.imgNubmer++;
          files.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files,
          imgNubmer,
        });
      }
    })
  },

  onReady() {
    // 页面加载完成
  },
  onShow() {
    // 页面显示
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'My App',
      desc: 'My App description',
      path: 'pages/index/index',
    };
  },
});
